package org.dna.metronomo.persistence.impl;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.dna.metronomo.persistence.DBUtils;
import org.dna.metronomo.persistence.IModuleDAO;
import org.dna.metronomo.persistence.impl.annotations.DAOFactory;
import org.tigris.scarab.mapper.IssueTypeMapper;
import org.tigris.scarab.mapper.IssueTypeMapperTest;
import org.tigris.scarab.model.IssueType;
import org.tigris.scarab.model.Module;

/**
 *
 * @author andrea
 */
public class Utils {

    static Module insertAndReload(Module module) {
        IModuleDAO s_moduleDao = DAOFactory.createDAO(IBatisModuleDAO.class);
        s_moduleDao.insert(module);
        return s_moduleDao.findByID(0);
    }

    static IssueType insertAndReload(IssueType type) throws IOException {
        IssueType reloaded;
        Reader reader = Resources.getResourceAsReader(IssueTypeMapperTest.CONF_PATH);
        SqlSessionFactory s_sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = s_sqlSessionFactory.openSession();
        try {
            IssueTypeMapper mapper = session.getMapper(IssueTypeMapper.class);
            mapper.insert(type);
            session.commit();
            reloaded = mapper.selectByID(IssueTypeMapperTest.DEFAULT_ISSUE_TYPE_OFFSET_ID);
        } finally {
            session.close();
        }
        return reloaded;
    }
    
    static IssueType reloadIssueType(int id) throws IOException {
        IssueType reloaded;
        Reader reader = Resources.getResourceAsReader(IssueTypeMapperTest.CONF_PATH);
        SqlSessionFactory s_sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = s_sqlSessionFactory.openSession();
        try {
            IssueTypeMapper mapper = session.getMapper(IssueTypeMapper.class);
            reloaded = mapper.selectByID(id);
        } finally {
            session.close();
        }
        return reloaded;
    }

    /**
     * Remove all module inserted except the global parent with ID = 0 and reset
     * the index.
     */
    static void cleanupModuleTable() throws SQLException {
        DBUtils.executeSql("DELETE FROM SCARAB_MODULE WHERE MODULE_ID > 0");
        DBUtils.resetKeyColumn("SCARAB_MODULE", "MODULE_ID", 1);// because 0 is populated by Global parent
    }
}
